package com.ctl.algorithm; /**
 * <p>Title: Test</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.ctl.com</p>
 *
 * @author ctl
 * @version 1.1
 * @date 2024-07-15 15:11
 */

import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;

/**
 * 两个线程交叉顺序打印1到100  java代码
 */
public class AlternatePrintingWithExchanger {
    private static Exchanger<Integer> exchanger = new Exchanger<>();
    private final static int PRINT_NUM = 100;
    private static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {
        Thread thread2 = new Thread(new Printer(2, null), "Thread-2");
        Thread thread1 = new Thread(new Printer(1, thread2), "Thread-1");
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {

        }
        thread1.start();

    }

    static class Printer implements Runnable {
        private int parity; // 0 for even, 1 for odd
        private Thread thread; // 0 for even, 1 for odd

        public Printer(int parity, Thread thread) {
            this.parity = parity;
            this.thread = thread;
        }

        @Override
        public void run() {
            if (thread != null && parity == 1) {
                thread.start();
            }
            for (int i = parity; i <= parity + (PRINT_NUM / 2 - 1) * 2; i = i + 2) {
                try {
                    if (parity == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + i);
                        semaphore.release();
                        exchanger.exchange(i);
                    } else {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + ": " + i);
                        exchanger.exchange(i);
                    }
                } catch (InterruptedException e) {
                    System.out.println(e);
                }
            }
//            System.out.println(Thread.currentThread().getName() + ": over");
        }
    }
}
